package com.etc.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

public class QiniuCloudUtil {
    private static final Logger logger= LoggerFactory.getLogger(QiniuCloudUtil.class);

    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static String ACCESS_KEY = "4P-khPxfU2GD1WOpRIs9AYWU23h_IbHU0wrv-fNu";
    private static String SECRET_KEY = "8a57yrD3leuEf0ABt9t4v3_3K8Dk6v_0n_Vuih6S";
    //要上传的空间名
    private static String bucketname = "spingmvc-image";


    //上传到七牛后保存的文件名
    //String key="iphone11.jpg";
    //上传文件的路径
    //String FilePath="C:\Users\Administrator.USER-20190611ED\Desktop\iphone11.jpg"

    //密钥配置
    private static Auth auth=Auth.create(ACCESS_KEY,SECRET_KEY);

    //构建一个带指定Regin对象的配置类
    private static Configuration cfg = new Configuration(Region.huadong());
    //创建上传对象
    private static UploadManager uploadManager=new UploadManager(cfg);

    //测试域名
    private static String QINIU_IMAGE_DOMAIN="http://rdvnhho7k.hd-bkt.clouddn.com/";

    //简单上传
    public static String getUpToken(){
        return auth.uploadToken(bucketname);
    }

    /**
     * 普通上传
     * @param file 上传的文件对象
     * @return 上传结果消息
     * @throws IOException
     */
    public static String uploadImageFile(MultipartFile file) throws IOException{
        try {
            //获取源文件名
            String originalFilename = file.getOriginalFilename();
            //设置上传到七牛云保存的文件名
            StringBuffer storeFileName=new StringBuffer();
            storeFileName.append(UUID.randomUUID().toString().replaceAll("-","")).append(originalFilename.substring(originalFilename.lastIndexOf(".")));
            //调用put方法上传put文件(文件字节数组，存储文件名，上传凭证)
            Response res=uploadManager.put(file.getBytes(),storeFileName.toString(),getUpToken());
            if (res.isOK()){
                //打印返回的信息
                logger.info("++++++++"+res.bodyString());
                logger.info("++++++++++"+QINIU_IMAGE_DOMAIN+new ObjectMapper().readValue(res.bodyString(), HashMap.class).get("key").toString());
                //默认情况下，文件上传到七牛之后，在没有设置returnBody或者回调相关参数情况下，七牛返回给上传端的回复格式为hash和key，例如：{"hash":"Ftgm-CkWePc9fzMBTRNmPMhGBcSV","key":"qiniu.jpg"}
                //返回存储的文件名
                //JSON转Java: new ObjectMapper().readValue(res.bodyString(), HashMap.class).get("key").toString();
                //返回这个图片存储的地址
                return QINIU_IMAGE_DOMAIN+new ObjectMapper().readValue(res.bodyString(), HashMap.class).get("key").toString();
            }else {
                //请求失败时打印的异常的信息
                //使用日志工具输出异常的信息
                logger.error("七牛异常:"+res.toString());
                return null;
            }
        } catch (QiniuException e) {
            Response r=e.response;
            //请求失败时打印的异常的信息
            System.out.println(r.toString());
            //使用日志工具输出异常
            logger.error("七牛异常:"+r.toString());
            return null;
        }

    }

    /**
     * 下载文件-私有空间
     * @param fileName 下载文件名
     * @return 下载链接
     */
    public static String downloadURL(String fileName){
        //定义一个基础URL domain/key
        String publicURL=QINIU_IMAGE_DOMAIN+fileName;

        //调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间
        String downloadURL = auth.privateDownloadUrl(publicURL, 3600);
        //使用日志输出下载链接
        logger.info("++++++++++++"+downloadURL);
        //返回
        return downloadURL;

    }

    public static void main(String[] args) {
        QiniuCloudUtil.downloadURL("0be4162e4c6449a39a07ae49fe651f44.jpg");
    }



}
